<?php
namespace app\api\controller;

use app\lib\Show;
use think\Exception;
use think\facade\Log;

class Cart extends Auth {

    public function add() {
        $params = $this->request->param(["id", "num"], 0, "intval");
        if ($params["id"] <= 0 || $params["num"] <= 0) {
            return Show::fail("获取参数失败");
        }

        try{
            $params["user_id"] = $this->user["id"];
            $result = (new \app\api\business\Cart())->add($params);
            if ($result === false) {
                return Show::fail("购物车添加失败");
            }

            return Show::success("购物车添加成功");
        }catch (Exception $e){
            Log::error($e);
            return Show::fail("购物车添加失败");
        }
    }

    public function index() {
        try{
            $ids = $this->request->param("ids", "", "trim");
            $idArr = [];
            if ($ids) {
                $idArr = explode(",", $ids);
            }
            unset($ids);
            $result = (new \app\api\business\Cart())->listByUserOrIds($this->user["id"], $idArr);
            return Show::success("ok", $result);
        }catch (Exception $e){
            Log::error($e);
            return Show::fail("购物车获取数据失败");
        }
    }

    public function update() {
        $params = $this->request->param(["id", "num"], 0, "intval");
        if ($params["id"] <= 0 || $params["num"] <= 0) {
            return Show::fail("获取参数失败");
        }

        try{
            $params["user_id"] = $this->user["id"];
            $result = (new \app\api\business\Cart())->update($params);
            if ($result === false) {
                return Show::fail("购物车更新失败");
            }

            return Show::success("购物车更新成功");
        }catch (Exception $e){
            Log::error($e);
            return Show::fail("购物车更新失败");
        }
    }

    public function delete() {
        $params["id"] = $this->request->param("id", 0, "intval");
        if ($params["id"] <= 0) {
            return Show::fail("获取参数失败");
        }

        try{
            $params["user_id"] = $this->user["id"];
            $result = (new \app\api\business\Cart())->delete($params);
            if ($result === false) {
                return Show::fail("购物车删除失败");
            }

            return Show::success("购物车删除成功");
        }catch (Exception $e){
            Log::error($e);
            return Show::fail("购物车删除失败");
        }

    }
}